package com.infoland.afanmall.model.address.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.entity.UserInFoEntity;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.StatusBarKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.UserKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.model.address.adyncTask.AddressPickTask;
import com.infoland.afanmall.model.address.entity.AddressAllEntity;
import com.infoland.afanmall.model.eventBus.address.EventUpdateAddress;
import com.lzy.okgo.OkGo;
import com.wyj.floatlayout.FlowLayout;
import com.wyj.floatlayout.TagAdapter;
import com.wyj.floatlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import okhttp3.Call;

/**
 * 添加地址Activity
 */
public class AddressInsertActivity extends AppCompatActivity {
    @BindView(R.id.name)
    AppCompatEditText name;
    @BindView(R.id.phone)
    AppCompatEditText phone;
    @BindView(R.id.address)
    AppCompatEditText address;
    @BindView(R.id.xiang_xi)
    AppCompatEditText xiangXi;
    @BindView(R.id.switch_button)
    SwitchCompat switchButton;
    @BindView(R.id.cart_back)
    ImageView cartBack;
    @BindView(R.id.toolbar)
    LinearLayout title;
    @BindView(R.id.insert)
    Button addressBtInsert;
    private int userId = -1;
    private int addressID = -1;
    @BindView(R.id.flag)
    EditText flag;
    TagAdapter<String> tagAdapter;
    //   输入法管理器
    private InputMethodManager mInputMethodManager;

    public int getLayout() {
        return R.layout.address_insert_activity;
    }


    //   获取登录信息
    public void getkLogin() {
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("response200 ---->   ", "  " + response200);
                    UserInFoEntity userInFoEntity = JSONObject.parseObject(response200, UserInFoEntity.class);
                    userId = userInFoEntity.getId();
                },
                success401 -> {
                    finish();
                    ToastUtils.showShort("登录失效，请先登录");
                },
                error -> {
                    finish();
                }
        ).post(CONST.USER_INFO + UserKit.getAccessToken(), new JSONObject(), this);
    }

    //打开地址选择器
    public void openAddressSelect() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {
                address.setText("");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                String s;
                if (county == null) {
                    s = province.getAreaName() + " " + city.getAreaName();
                } else {
                    s = province.getAreaName() + " " + city.getAreaName() + " " + county.getAreaName();
                }
                address.setText(s);
            }
        });
        task.execute("北京市", "北京市", "东城区");
    }

    @BindView(R.id.flow_layout)
    TagFlowLayout flowLayout;
    ArrayList<String> biaoQianList;

    //添加标签
    private void setBiaoQian() {
        biaoQianList = new ArrayList<>();
        biaoQianList.add("家");
        biaoQianList.add("公司");
        biaoQianList.add("学校");

        tagAdapter = new TagAdapter<String>(biaoQianList) {
            @Override
            public View getView(FlowLayout parent, int position, String flag) {
                View inflate = getLayoutInflater().inflate(R.layout.address_biao_qian, flowLayout, false);
                TextView viewById = inflate.findViewById(R.id.flag);
                viewById.setText(flag);
                return inflate;
            }
        };
//        flowLayout.setAdapter(tagAdapter);
//        flowLayout.setOnTagClickListener((view, position, parent) -> {
//            flowLayout.unCheckAll();
//            ((TagView) view).setChecked(true);
//            return true;
//        });
        flowLayout.unCheckAll();
        flowLayout.updateCheckAll();
        flowLayout.setCheckFirst();
    }

    //   开始添加地址
    private void insertOrUpdate(int userId, int addressId) {
        JSONObject para = getInsertOrUpdatePara(userId, addressId);
        new OkHttpKit().send(
                response200 -> {
                    JSONObject jsonObject = JSONObject.parseObject(response200);
                    LogKit.E("添加地址---->   ", "  " + response200);
                    if (jsonObject.getBoolean("success")) {
                        finish();
                    } else {
                        ToastUtils.showShort("添加失败");
                        finish();
                    }
                },
                success401 -> {
                    ToastUtils.showShort("添加失败");
                    LogKit.E("  Exception ", "  " + success401);
                    finish();
                },
                error -> {
                    ToastUtils.showShort("添加失败");
                    LogKit.E("  Exception ", "  " + error);
                    finish();
                }
        ).post(CONST.SAVE_OR_UPDATE_ADDRESS + UserKit.getAccessToken(), para, this);
    }

    //    获取地址参数
    @NonNull
    private JSONObject getInsertOrUpdatePara(int userId, int addressId) {
        JSONObject para = new JSONObject();
        if (addressId != -1) {
            para.put("id", addressId);//关联用户ID
        }
        para.put("user_id", userId);//关联用户ID
//        Set<Integer> selectedList = flowLayout.getSelectedList();
//        Iterator<Integer> iterator = selectedList.iterator();
//        Integer next = iterator.next();
        String biaoqian = "";
//        if (biaoQianList.size() >= next) {
//            biaoqian = biaoQianList.get(next);
//        }
        String name = this.name.getText().toString();
        String phone = this.phone.getText().toString();
        String address = this.address.getText().toString();
        String xaingxi = xiangXi.getText().toString();
        boolean checked = switchButton.isChecked();
        String[] split = address.split(" ");

        if (split.length == 3) {
            para.put("province_name", split[0]); //省
            para.put("city_name", split[1]);//	市
            para.put("area_name", split[2]);//区
        } else if (split.length == 2) {
            para.put("province_name", split[0]); //省
            para.put("city_name", split[1]);//	市
            para.put("area_name", "");//区
        }
        para.put("address_label", biaoqian);//标签
        para.put("user_address", xaingxi);//详细地址
        para.put("user_addr_num", "");//邮政编码
        para.put("receiver_name", name);//收货人姓名
        para.put("receiver_tel", phone);//收货人手机号
        para.put("type", 1);//1 个人，2 企业
        para.put("default_flag", checked ? 1 : 0);//0非默认地址，1默认地址
        para.put("province_city_area", address);//省市区
        LogKit.E("goodsSpecJson   ", "  " + para.toJSONString());
        return para;
    }

    @OnClick({R.id.insert_flag, R.id.switch_button, R.id.cart_back, R.id.insert, R.id.address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            /*** 添加地址**/
            case R.id.insert:
                if (checkName()) {
                    if (ToolsKit.isPhone(phone.getText().toString())) {
                        if (checkAddress()) {
                            if (checkXiangXi()) {
                                insertOrUpdate(userId, addressID);
                            } else {
                                ToastUtils.showShort("请正确输入详细地址");
                            }
                        } else {
                            ToastUtils.showShort("请正确输入地址");
                        }
                    } else {
                        ToastUtils.showShort("请正确输入手机号");
                    }
                } else {
                    ToastUtils.showShort("请输入收货人姓名");
                }
                break;
            /*** 退出**/
            case R.id.cart_back:
                finish();
                break;
            /*** 选择地区**/
            case R.id.address:
                openAddressSelect();
                break;
            /*** 取消所有焦点**/
            case R.id.switch_button:
                clearAllFcouse();
                break;
            /*** 添加标签**/
            case R.id.insert_flag:
                String trim = flag.getText().toString().trim();
                biaoQianList.add(trim);
                tagAdapter.notifyDataChanged();
                flag.setText("");
                clearAllFcouse();
                break;
        }
    }


    //清除所有焦点
    private void clearAllFcouse() {
        name.clearFocus();
        phone.clearFocus();
        address.clearFocus();
        xiangXi.clearFocus();
        flag.clearFocus();
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        ButterKnife.bind(this);
        StatusBarKit.immersiveBlackTitleText(this, title);
        ToolsKit.setEditHide(address);
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getkLogin();
        setBiaoQian();
    }

    private boolean checkXiangXi() {
        return xiangXi.getText().toString().length() >= 6;
    }

    private boolean checkAddress() {
        return address.getText().toString().split("").length >= 2;
    }

    private boolean checkName() {
        return name.getText().toString().length() > 0;
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(AddressInsertActivity.this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(AddressInsertActivity.this);
    }

    //    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEvent(EventUpdateAddress event) {
//
//    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onStickyEvent(EventUpdateAddress event) {
        if (event.isIsok()) {
            addressID = event.getId();
            getAddressById(event.getId());
            LogKit.E("aaaa ---->   ", "  onStickyEvent  userId=  " + event.getId());
        }
    }

    //查询地址信息
    private void getAddressById(int id) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        new OkHttpKit().send(
                response200 -> {
                    AddressAllEntity addressAllEntity = JSONObject.parseObject(response200, AddressAllEntity.class);
                    updateUi(addressAllEntity);
                },
                success401 -> {
                    ToastUtils.showShort("操作失败");
                    LogKit.E("  查询地址信息---> ", success401);
                },
                error -> {
                    ToastUtils.showShort("操作失败");
                    LogKit.E("  查询地址信息---> ", error);
                }
        ).post(CONST.SELECT_ADDRESS_BY_ID + UserKit.getAccessToken(), jsonObject, this);
    }

    private void updateUi(AddressAllEntity addressAllEntity) {
        name.setText(addressAllEntity.getReceiver_name());
        phone.setText(addressAllEntity.getReceiver_tel());
        address.setText(addressAllEntity.getProvince_city_area());
        xiangXi.setText(addressAllEntity.getUser_address());
        switchButton.setChecked(addressAllEntity.getDefault_flag() != 0);
        if (addressAllEntity.getAddress_label() == null || "".equals(addressAllEntity.getAddress_label().trim())) {

        } else {
            biaoQianList.add(addressAllEntity.getAddress_label());
            tagAdapter.notifyDataChanged();
//            ((TagView) flowLayout.getChildAt(0)).setChecked(false);
//            ((TagView) flowLayout.getChildAt(3)).setChecked(true);
        }
        clearAllFcouse();
    }

    @Override
    protected void onDestroy() {
        OkGo.getInstance().cancelTag(this);
        super.onDestroy();
    }
}
